package com.getpebble.android.common.auth;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import com.getpebble.android.common.core.trace.Trace;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.koushikdutta.ion.Response;
import java.io.IOException;

public class PblSessionManager {
    private static final String TAG = PblSessionManager.class.getSimpleName();
    private static AccountManager sAccountManager = null;
    private static PblSessionManager sInstance = null;
    private String mAccessToken = null;
    private Account mUserAccount = null;

    private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
        private OnTokenAcquired() {
        }

        public void run(AccountManagerFuture<Bundle> result) {
            try {
                PblSessionManager.this.mAccessToken = ((Bundle) result.getResult()).getString("authtoken");
                PblSessionManager.this.handleToken();
            } catch (IOException e) {
                Trace.error(PblSessionManager.TAG, "Failed to retrieve token, unable to read from disk!", e);
                e.printStackTrace();
            } catch (AuthenticatorException e2) {
                Trace.error(PblSessionManager.TAG, "Failed to retrieve token, unable to communicate with Authenticator!", e2);
                e2.printStackTrace();
            } catch (OperationCanceledException e3) {
                Trace.error(PblSessionManager.TAG, "Failed to retrieve token, unable to continue, operation has been canceled!", e3);
                e3.printStackTrace();
            }
        }
    }

    private PblSessionManager(Context context) {
        sAccountManager = AccountManager.get(context);
        if (sAccountManager != null) {
            fetchUserAccount();
        }
    }

    private static Account parsePebbleAccount(Account[] accounts) {
        for (Account account : accounts) {
            if ("com.getpebble.android".equalsIgnoreCase(account.type)) {
                return account;
            }
        }
        return null;
    }

    public static Account getPebbleAccount() {
        if (sAccountManager != null) {
            Account[] accounts = sAccountManager.getAccountsByType("com.getpebble.android");
            if (sInstance != null) {
                sInstance.setSyncAccount(parsePebbleAccount(accounts));
                return sInstance.getUserAccount();
            }
        }
        return null;
    }

    private void setSyncAccount(Account account) {
        this.mUserAccount = account;
        if (this.mUserAccount != null) {
            verifyAccountToken();
        }
    }

    public String peekAuthToken() {
        Account account = getPebbleAccount();
        if (account != null) {
            return sAccountManager.peekAuthToken(account, "com.getpebble");
        }
        Trace.warning(TAG, "peekAuthToken: account is null");
        return null;
    }

    private void verifyAccountToken() {
        try {
            this.mAccessToken = sAccountManager.peekAuthToken(this.mUserAccount, "com.getpebble");
            handleToken();
        } catch (IllegalArgumentException e) {
            this.mUserAccount = null;
        }
    }

    public static JsonObject getUserFromResponse(Response<JsonObject> responseString) {
        int responseCode = 0;
        if (!(responseString == null || responseString.getHeaders() == null)) {
            responseCode = responseString.getHeaders().getResponseCode();
        }
        if (responseCode != 200) {
            Trace.error(TAG, "Failed to get account info. Response Code = " + responseCode);
            return null;
        }
        JsonObject result = (JsonObject) responseString.getResult();
        if (result == null) {
            Trace.error(TAG, "onCompleted: result was null");
            return null;
        }
        JsonArray userArray = result.getAsJsonArray("users");
        if (userArray != null && userArray.size() >= 1) {
            return userArray.get(0).getAsJsonObject();
        }
        Trace.error(TAG, "onCompleted: user array was null");
        return null;
    }

    private void handleToken() {
        boolean isValidToken = false;
        if (!TextUtils.isEmpty(this.mAccessToken)) {
            isValidToken = true;
        }
        if (!isValidToken && this.mUserAccount != null) {
            sAccountManager.getAuthToken(this.mUserAccount, "com.getpebble", null, true, new OnTokenAcquired(), null);
        }
    }

    public void createAccount(String username, String password, String accessToken, String id, String uid) {
        createAccount(username, password, accessToken, id, uid, null);
    }

    public void createAccount(String username, String password, String accessToken, String id, String uid, Bundle bootConfig) {
        Account account = new Account(username, "com.getpebble.android");
        sAccountManager.addAccountExplicitly(account, password, bootConfig);
        sAccountManager.invalidateAuthToken("com.getpebble.android", null);
        sAccountManager.setAuthToken(account, "com.getpebble", accessToken);
        this.mAccessToken = accessToken;
        sAccountManager.setUserData(account, "id", id);
        sAccountManager.setUserData(account, "uid", uid);
        setSyncAccount(account);
    }

    public void removeAccount() {
        if (!(sAccountManager == null || this.mUserAccount == null)) {
            sAccountManager.removeAccount(this.mUserAccount, null, null);
        }
        this.mAccessToken = null;
        setSyncAccount(null);
    }

    public static PblSessionManager createInstance(Context context) {
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        }
        if (sInstance == null) {
            sInstance = new PblSessionManager(context);
        }
        return sInstance;
    }

    public Account getUserAccount() {
        return this.mUserAccount;
    }

    public Account fetchUserAccount() {
        if (sAccountManager == null) {
            return null;
        }
        setSyncAccount(parsePebbleAccount(sAccountManager.getAccountsByType("com.getpebble.android")));
        return getUserAccount();
    }

    public String getId(Account account) {
        String id = sAccountManager.getUserData(account, "id");
        if (TextUtils.isEmpty(id)) {
            Trace.warning(TAG, "Null / empty 'id' in account " + account.toString());
        }
        return id;
    }

    public String getUid(Account account) {
        String uid = sAccountManager.getUserData(account, "uid");
        if (TextUtils.isEmpty(uid)) {
            Trace.warning(TAG, "Null / empty 'uid' in account " + account.toString());
        }
        return uid;
    }

    public void setId(Account account, String id) {
        sAccountManager.setUserData(account, "id", id);
    }

    public void setUid(Account account, String uid) {
        sAccountManager.setUserData(account, "uid", uid);
    }
}
